package cn.itsub.sodo;

import java.awt.AlphaComposite;
import java.awt.Composite;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import cn.itsub.sodo.cache.TextureCache;
import cn.itsub.sodo.core.Texture2D;
import cn.itsub.sodo.util.ImageUtil;

/**
 * 精灵
 * @author loopcc
 *
 */
public class Sprite extends Node {
	
	private Texture2D texture = null;
	private String fileName;
	
	public Sprite() {
		// TODO Auto-generated constructor stub
	}
	public Sprite(String fileName) {
		this.fileName = fileName;

		texture = TextureCache.getInstance().add(fileName);
		this.size = texture.getSize();

	}
	/* ------------------------------ */
	
	
	
	
	@Override
	public void draw(Graphics2D g) {
		Graphics2D g2 = (Graphics2D) g;
		Composite oldComposite = g.getComposite();
		
		Sprite sp = this;

		BufferedImage img = sp.getTexture().getImage();

		if (flipX||flipY) {
			img = ImageUtil.flip(img, flipX, flipY);
		}

		int width = (int) (img.getWidth(null)*scaleX);
		int height = (int) (img.getHeight(null)*scaleY);
		int x = (int)sp.getWindowPosition().x;
		int y = (int)sp.getWindowPosition().y;
		int drawX = (int) (x-width*(1.0-anchorX));
		int drawY = (int) (y-height*(1.0-anchorY));
		double anchorPointX = drawX+width*this.anchorX;
		double anchorPointY = drawY+height*this.anchorY;
		double rotateRadians = Math.toRadians(this.rotation);

		AlphaComposite alphaComposite=AlphaComposite.getInstance(AlphaComposite.SRC_OVER, this.opacity);
		
		g2.setComposite(alphaComposite);//透明度
		g2.rotate(rotateRadians, anchorPointX, anchorPointY);

		g2.drawImage(img, drawX, drawY, width, height, null);
		g2.setComposite(oldComposite);//透明度
		g2.rotate(-rotateRadians, anchorPointX, anchorPointY);

		//g2.dispose();


	}
	/* ------------------------------ */
	public Texture2D getTexture() {
		return texture;
	}
	public void setTexture(Texture2D texture) {
		this.texture = texture;
	}
	
}
